package com.nervenets.shopping.config.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
import cn.binarywang.wx.miniapp.message.WxMaXmlOutMessage;
import com.google.common.collect.Maps;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.curator.shaded.com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@EnableConfigurationProperties(WxMAProperties.class)
public class WxMAConfiguration {
    private static WxMAProperties properties = null;
    private static Map<String, WxMaMessageRouter> routers = Maps.newHashMap();
    private static Map<String, WxMaService> maServices = Maps.newHashMap();

    @Autowired
    public WxMAConfiguration(WxMAProperties properties) {
        WxMAConfiguration.properties = properties;
    }

    public static Map<String, WxMaMessageRouter> getRouters() {
        return routers;
    }

    public static WxMaService getMaService(String appid) {
        WxMaService wxService = maServices.get(appid);
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        return wxService;
    }

    public static WxMaService getMaService(int index) {
        WxMaService wxService = maServices.get(WxMAConfiguration.properties.getConfigs().get(index).getAppid());
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("未找到对应index=[%s]的配置，请核实！", index));
        }

        return wxService;
    }

    @Bean
    public Object services() {
        maServices = WxMAConfiguration.properties.getConfigs()
                .stream()
                .map(a -> {
                    WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
                    config.setAppid(a.getAppid());
                    config.setSecret(a.getSecret());
                    config.setToken(a.getToken());
                    config.setAesKey(a.getAesKey());
                    config.setMsgDataFormat(a.getMsgDataFormat());

                    WxMaService service = new WxMaServiceImpl();
                    service.setWxMaConfig(config);
                    routers.put(a.getAppid(), this.newRouter(service));
                    return service;
                }).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a));

        return Boolean.TRUE;
    }

    private WxMaMessageRouter newRouter(WxMaService service) {
        final WxMaMessageRouter router = new WxMaMessageRouter(service);
        router.rule().handler((wxMessage, map, wxMaService, wxSessionManager) -> {
            System.out.println("收到消息：" + wxMessage.toString());
            service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为：" + wxMessage.toJson())
                    .toUser(wxMessage.getFromUser()).build());
            return WxMaXmlOutMessage.builder().build();
        }).next().rule().async(false).content("模板").handler((wxMessage, map, wxMaService, wxSessionManager) -> {
            service.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder()
                    .templateId("此处更换为自己的模板id")
                    .data(Lists.newArrayList(
                            new WxMaSubscribeMessage.MsgData("keyword1", "339208499")))
                    .toUser(wxMessage.getFromUser())
                    .build());
            return WxMaXmlOutMessage.builder().build();
        }).end().rule().async(false).content("文本").handler((wxMessage, map, wxMaService, wxSessionManager) -> {
            service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息")
                    .toUser(wxMessage.getFromUser()).build());
            return WxMaXmlOutMessage.builder().build();
        }).end().rule().async(false).content("图片").handler((wxMessage, map, wxMaService, wxSessionManager) -> {
            try {
                WxMediaUploadResult uploadResult = service.getMediaService()
                        .uploadMedia("image", "png",
                                ClassLoader.getSystemResourceAsStream("tmp.png"));
                service.getMsgService().sendKefuMsg(
                        WxMaKefuMessage
                                .newImageBuilder()
                                .mediaId(uploadResult.getMediaId())
                                .toUser(wxMessage.getFromUser())
                                .build());
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
            return WxMaXmlOutMessage.builder().build();
        }).end().rule().async(false).content("二维码").handler((wxMessage, map, wxMaService, wxSessionManager) -> {
            try {
                final File file = service.getQrcodeService().createQrcode("123", 430);
                WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file);
                service.getMsgService().sendKefuMsg(
                        WxMaKefuMessage
                                .newImageBuilder()
                                .mediaId(uploadResult.getMediaId())
                                .toUser(wxMessage.getFromUser())
                                .build());
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
            return WxMaXmlOutMessage.builder().build();
        }).end();
        return router;
    }
}
